const model = require('../models/userModel'),
  redisClusterUtils = require('../models/redisModel'),
  errCode = require('../../conf/errorCode'),
  wrap = require('../helper/wrap'),
  conf = require('../../conf/const'),
  util = require('../helper/util'),
  sms = require('../helper/sms'),
  _ = require('lodash'),
  logger = require('../helper/logger'),
  {parseIntPageSize} = require('./commonService');

var tagLogger = new logger.TagLogger('USER_SERVICE');

exports.getByAccountName = function(accountName, page, size, callback) {
  let errMsgs = null;
  [errMsgs, page, size] = parseIntPageSize(page, size);

  accountName = accountName == null ? '' : accountName;

  if (errMsgs == null)
    model.getByAccountName(accountName, page, size, callback);
  else callback({errNo: errCode.INVALID_PARAM_ERROR, extraMsgs: errMsgs});
};

//加入黑名单,支持批量加入
exports.blockUserByIds = function(ids, callback) {
  if (_.isString(ids)) {
    ids = ids.trim().split(',');
    if (
      !_.every(ids, function(value) {
        return util.isIntegerLike(value);
      })
    ) {
      return callback({errNo: errCode.INVALID_FORMAT_ERROR, extraMsgs: 'ids'});
    }
  } else if (_.isNumber(ids)) {
    ids = [ids];
  } else if (
    !_.isArray(ids) ||
    !_.every(ids, function(value) {
      return util.isIntegerLike(value);
    })
  ) {
    return callback({errNo: errCode.INVALID_FORMAT_ERROR});
  }
  if (ids.length == 0) {
    return callback(null, {updated: 0});
  }

  model.blockUserByIds(ids, (err, result) => {
    if (err) return callback(err);
    return callback(null, {
      updated: result.changedRows,
    });
  });
};

exports.generateMobileMsgCode = function(mobile, callback) {
  var tmp = util.firstKeyOfNull({mobile}, ['mobile']);
  if (tmp != null) {
    return callback({errNo: errCode.LESS_OF_DATA_ERROR, extraMsgs: tmp});
  }

  let msgCode = util.buildRandomMsgCode();

  // 验证码放入redis，并在60s后超时，用于后续校验
  redisClusterUtils.storeMobileMsgCode(mobile, msgCode);

  sms
    .sendSMS({
      PhoneNumbers: mobile,
      SignName: '咖加车评',
      TemplateCode: 'SMS_130250109',
      TemplateParam: `{"code":"${msgCode}"}`,
    })
    .then(
      res => {
        let {Code} = res;
        if (Code === 'OK') {
          //处理返回参数
          return callback(null);
        }
      },
      err => {
        tagLogger.error(err);
        return callback({errNo: errCode.SMS_SDK_ERROR});
      },
    );
};

exports.getUserInfo = function(userId, callback) {
  model.getUserInfo(userId, callback);
};

exports.getUserListByNamePrefix = function(namePrefix, callback) {
  model.getUserListByNamePrefix(namePrefix, callback);
};

exports.getUserByPage = function(namePrefix, page, size, callback) {
  let errMsgs = null;
  [errMsgs, page, size] = parseIntPageSize(page, size);

  if (errMsgs == null)
    model.getUserByPage(namePrefix, page, size, (err, _rel) => {
      _rel.list.map(item => {
        item.createTime = util.formatTime(item.createTime);
      });

      if (err) {
        return callback(err);
      } else {
        return callback(null, _rel);
      }
    });
  else callback({errNo: errCode.INVALID_PARAM_ERROR, extraMsgs: errMsgs});
};

exports.modifyUserRole = (uid, role, callback) => {
  var tmp = util.firstKeyOfNull({uid}, ['uid']);
  if (tmp != null) {
    return callback({errNo: errCode.LESS_OF_DATA_ERROR, extraMsgs: tmp});
  }
  model.modifyUserRole(uid, role, callback);
};
